package oceanpayment

import (
    "fmt"
	"strings"
	"io/ioutil"
	"net/http"
	"net/url"
	"encoding/xml"
	"crypto/sha256"
	"thirdpaysdk/utils/mapstruct"
	//"github.com/astaxie/beego"
)

type Auth struct {
	requrl     string
	appsecret  string
}

func NewSDK(restURL string) *Auth {
	return &Auth{requrl:restURL, appsecret:""}
}

func (this *Auth) Request(request,response interface{}) ([]byte, error) {
	params := mapstruct.Struct2Map(request, "form")
	urlParams := url.Values{}
	for k, v := range params {
		urlParams.Add(k, fmt.Sprintf("%v", v))
	}
	body := strings.NewReader(urlParams.Encode())
	reqHttp, err := http.NewRequest("POST", this.requrl, body)
	if err != nil {
		return nil, err
	}
	reqHttp.Header.Set("Content-Type", "application/x-www-form-urlencoded") //必须
	client := &http.Client{}
	resp, err := client.Do(reqHttp)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	//beego.Debug("rsp data:", string(data))
	err = xml.Unmarshal(data, &response)
	if err != nil {
	    return nil, err
	}	
	return data, nil
}

// SHA256 sha256
func sHA256(data []byte) []byte {
	h := sha256.New()
	h.Write(data)
	return h.Sum(nil)
}



